using UnityEngine;
using UnityEngine.UI;
using QFramework;
using System.Collections.Generic;
using Game.CheseBoard;
using Game.Assets.Scripts.Manager;

namespace Game.UI
{
    public class UIBagPanelData : UIPanelData
    {
        public BagCell bag;
    }
    public partial class UIBagPanel : UIPanel, IController
    {
        [SerializeField] UIBagSlot prefab;
        [SerializeField] Transform parent;
        [SerializeField] Button closeBtn;
        [SerializeField] Text curCapacityText;

        List<UIBagSlot> _canceSlots = new List<UIBagSlot>();
        private void Awake()
        {
            closeBtn.onClick.AddListener(() => UIKit.ClosePanel(this));
        }
        public IArchitecture GetArchitecture()
        {
            return APP.Interface;
        }

        protected override void OnInit(IUIData uiData = null)
        {
            mData = uiData as UIBagPanelData ?? new UIBagPanelData();
            // please add init code here
        }

        protected override void OnOpen(IUIData uiData = null)
        {
            for (int i = 0; i < mData.bag.BagGrids.Count; i++)
            {
                CreatSlot(mData.bag.BagGrids[i]);
            }
            UpdateCapacityText();

            TypeEventSystem.Global.Register<BuyBagGridEvent>(BuySlot);
            TypeEventSystem.Global.Register<PutOutCellEvent>(PutOutCell);
        }


        protected override void OnShow()
        {
        }

        protected override void OnHide()
        {
        }

        protected override void OnClose()
        {
            TypeEventSystem.Global.UnRegister<BuyBagGridEvent>(BuySlot);
            TypeEventSystem.Global.UnRegister<PutOutCellEvent>(PutOutCell);
            TypeEventSystem.Global.Send<CloseBagPanelEvent>();
        }

        private void Slot_OnClickBuyEvt(int gridCount)
        {
            mData.bag.BuyGrid(gridCount);
        }
        private void Slot_OnClickPutOutEvt(int gridCount)
        {
            mData.bag.PutOut(gridCount);
        }

        void CreatSlot(BagCell.BagGrid grid)
        {
            UIBagSlot slot = Instantiate(prefab, parent);
            slot.OnClickBuyEvt += Slot_OnClickBuyEvt;
            slot.OnClickPutOutEvt += Slot_OnClickPutOutEvt;
            slot.SetData(grid);
            _canceSlots.Add(slot);
        }
        void BuySlot(BuyBagGridEvent grid)
        {
            _canceSlots[_canceSlots.Count - 1].SetData(mData.bag.BagGrids[mData.bag.BagGrids.Count - 2]);
            CreatSlot(grid.buyGrid);
            UpdateCapacityText();
        }
        void PutOutCell(PutOutCellEvent put)
        {
            _canceSlots[put.gradCount - 1].SetData(put.grid);
            UpdateCapacityText();
        }
        void UpdateCapacityText()
        {
            (int, int) capacity = mData.bag.GetCapacity();
            curCapacityText.text = string.Format(LanguageDef.DQRL, capacity.Item1, capacity.Item2);
        }
    }
}
